package com.gviiii.baiduai.file;

import cn.hutool.core.util.ImageUtil;
import com.gviiii.baiduai.pojo.ImageResultInfo;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 图片剪切处理类
 */
public class ImageFile {

    public static void cutImage(File srcFile, File destFile, Rectangle rectangle) {
        ImageUtil.cut(srcFile, destFile, rectangle);
    }

    /**
     * 根据识别结果剪切图片
     * @param srcFile
     * @param destFile
     * @param location
     */
    public static void cutImage(File srcFile, File destFile, ImageResultInfo.ResultsBean.LocationBean location) {
        try {
            BufferedImage read = ImageIO.read(srcFile);
            BufferedImage subimage = read.getSubimage(location.getLeft(), location.getTop(), location.getWidth(), location.getHeight());
            ImageIO.write(subimage,srcFile.getName().substring(srcFile.getName().lastIndexOf(".")+1),destFile);
        } catch (Exception e) {
            cutImage(srcFile, destFile, new Rectangle(location.getLeft(),location.getTop(),location.getWidth(),location.getHeight()));
        }
    }
}
